<?php
require_once 'Database.php';

/**
 * CDK码管理类
 */
class CDKManager {
    private $db;

    public function __construct() {
        $this->db = Database::getInstance();
    }

    /**
     * 生成CDK码
     */
    public function generateCDK($length = 16) {
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $cdk = '';
        $max = strlen($characters) - 1;
        
        for ($i = 0; $i < $length; $i++) {
            $cdk .= $characters[random_int(0, $max)];
        }
        
        // 添加分隔符，格式：XXXX-XXXX-XXXX-XXXX
        return substr($cdk, 0, 4) . '-' . substr($cdk, 4, 4) . '-' . 
               substr($cdk, 8, 4) . '-' . substr($cdk, 12, 4);
    }

    /**
     * 批量生成CDK码
     */
    public function batchGenerateCDK($count, $productId, $length = 16) {
        $cdks = [];
        for ($i = 0; $i < $count; $i++) {
            $cdk = $this->generateCDK($length);
            $cdks[] = $cdk;
            $this->addCDK($productId, $cdk);
        }
        return $cdks;
    }

    /**
     * 添加CDK码
     */
    public function addCDK($productId, $cdk = null, $status = 'available') {
        if ($cdk === null) {
            $cdk = $this->generateCDK();
        }
        $sql = "INSERT INTO cdks (cdk_code, product_id, status, created_at) VALUES (?, ?, ?, NOW())";
        return $this->db->query($sql, [$cdk, $productId, $status]);
    }

    /**
     * 删除CDK
     */
    public function deleteCDK($id)
    {
        $sql = "DELETE FROM cdks WHERE id = ?";
        return $this->db->query($sql, [$id]);
    }

    /**
     * 获取CDK统计信息
     */
    public function getCDKStatistics()
    {
        $sql = "SELECT 
                COUNT(*) as total_cdks,
                SUM(CASE WHEN status = 'available' THEN 1 ELSE 0 END) as available_cdks,
                SUM(CASE WHEN status = 'used' THEN 1 ELSE 0 END) as used_cdks,
                SUM(CASE WHEN status = 'expired' THEN 1 ELSE 0 END) as expired_cdks,
                COUNT(DISTINCT product_id) as product_count
                FROM cdks";
        
        $result = $this->db->query($sql);
        return !empty($result) ? $result[0] : [
            'total_cdks' => 0,
            'available_cdks' => 0,
            'used_cdks' => 0,
            'expired_cdks' => 0,
            'product_count' => 0
        ];
    }

    /**
     * 使用CDK码
     */
    public function useCDK($cdkId, $orderId) {
        $sql = "UPDATE cdks SET status = 'used', order_id = ?, used_at = NOW() WHERE id = ? AND status = 'available'";
        return $this->db->query($sql, [$orderId, $cdkId]);
    }

    /**
     * 根据订单ID获取CDK码
     */
    public function getCDKByOrderId($orderId) {
        $sql = "SELECT c.*, p.name as product_name FROM cdks c 
                LEFT JOIN products p ON c.product_id = p.id 
                WHERE c.order_id = ?";
        $result = $this->db->query($sql, [$orderId]);
        return !empty($result) ? $result[0] : null;
    }

    /**
     * 获取商品的CDK码列表
     */
    public function getCDKsByProduct($productId, $status = null) {
        $sql = "SELECT * FROM cdks WHERE product_id = ?";
        $params = [$productId];
        
        if ($status) {
            $sql .= " AND status = ?";
            $params[] = $status;
        }
        
        $sql .= " ORDER BY created_at DESC";
        return $this->db->query($sql, $params);
    }

    /**
     * 验证CDK码是否可用
     */
    public function validateCDK($cdkCode) {
        $sql = "SELECT * FROM cdks WHERE cdk_code = ? AND status = 'available'";
        $result = $this->db->query($sql, [$cdkCode]);
        return !empty($result) ? $result[0] : null;
    }

    /**
     * 获取可用的CDK码
     */
    public function getAvailableCDK($productId) {
        $sql = "SELECT * FROM cdks WHERE product_id = ? AND status = 'available' LIMIT 1";
        $result = $this->db->query($sql, [$productId]);
        return !empty($result) ? $result[0] : null;
    }

    /**
     * 批量删除CDK码
     */
    public function batchDeleteCDK($cdkIds) {
        if (empty($cdkIds)) return 0;
        
        $placeholders = str_repeat('?,', count($cdkIds) - 1) . '?';
        $sql = "DELETE FROM cdks WHERE id IN ($placeholders)";
        return $this->db->query($sql, $cdkIds);
    }

    /**
     * 获取CDK码统计信息（带产品ID）
     */
    public function getCDKStatisticsByProduct($productId = null) {
        $sql = "SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN status = 'available' THEN 1 ELSE 0 END) as available,
                SUM(CASE WHEN status = 'used' THEN 1 ELSE 0 END) as used
                FROM cdks";
        
        $params = [];
        if ($productId) {
            $sql .= " WHERE product_id = ?";
            $params[] = $productId;
        }
        
        $result = $this->db->query($sql, $params);
        return !empty($result) ? $result[0] : null;
    }

    /**
     * 获取所有CDK码
     */
    public function getAllCDKs() {
        $sql = "SELECT c.*, p.name as product_name FROM cdks c 
                LEFT JOIN products p ON c.product_id = p.id 
                ORDER BY c.created_at DESC";
        return $this->db->query($sql);
    }

    /**
     * 为订单分配CDK码
     */
    public function assignCDK($orderId) {
        // 获取订单信息
        $sql = "SELECT product_id FROM orders WHERE id = ?";
        $order = $this->db->query($sql, [$orderId]);
        
        if (empty($order)) {
            return false;
        }
        
        $productId = $order[0]['product_id'];
        
        // 获取可用的CDK码
        $availableCDK = $this->getAvailableCDK($productId);
        if (!$availableCDK) {
            return false;
        }
        
        // 使用CDK码
        $result = $this->useCDK($availableCDK['id'], $orderId);
        if ($result) {
            return $availableCDK['cdk_code'];
        }
        
        return false;
    }

    /**
     * 导入CDK码
     */
    public function importCDKs($cdkList, $productId) {
        $successCount = 0;
        $errorCount = 0;
        
        foreach ($cdkList as $cdk) {
            $cdk = trim($cdk);
            if (!empty($cdk)) {
                try {
                    $this->addCDK($productId, $cdk);
                    $successCount++;
                } catch (Exception $e) {
                    $errorCount++;
                }
            }
        }
        
        return [
            'success' => $successCount,
            'error' => $errorCount
        ];
    }
}
